package exercises.newcoder.solution;

/**
 * <a href="https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e?tpId=188&&tqId=38590&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking">
 * NC109 岛屿数量</a><br/>
 *
 * @author or2
 * @Description 给一个01矩阵，1代表是陆地，0代表海洋， 如果两个1相邻，那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
 * 岛屿: 相邻陆地可以组成一个岛屿（相邻:上下左右） 判断岛屿个数。
 * @create 2021年09月03日 时间: 10:47
 */
public class NumsOfIsland2 {
    /**
     * 判断岛屿数量
     * @param grid char字符型二维数组
     * @return int整型
     */
    public int solve (char[][] grid) {
        int nLength = grid.length;
        int mLength = grid[0].length;

        int ans = 0;

        for (int i = 0; i < nLength; i++) {
            for (int j = 0; j < mLength; j++) {
                if (grid[i][j] == 0) {
                    continue;
                }

                ans++;
                dfs(grid, i, j);
            }
        }

        return ans;
    }

    private void dfs(char[][] grid, int i, int j) {
        int nLength = grid.length;
        int mLength = grid[0].length;

        grid[i][j] = 0;
        int nextI = i + 1;
        if (nextI < nLength && grid[nextI][j] == 1) {
            dfs(grid, nextI, j);
        }
        int nextJ = j + 1;
        if (nextJ < mLength && grid[i][nextJ] == 1) {
            dfs(grid, i, nextJ);
        }
        int preI = i - 1;
        if (preI >= 0 && grid[preI][j] == 1) {
            dfs(grid, preI, j);
        }
        int preJ = j - 1;
        if (preJ >= 0 && grid[i][preJ] == 1) {
            dfs(grid, i, preJ);
        }
    }
}